import React from 'react'
import { connect } from 'react-redux'
import { Row, Col, Icon, Button, Card, Modal, message } from 'antd'
import Condition from 'components/condition'
const { If, Else } = Condition;
import Dragger from 'components/template/dragger/dragger';
import {deepCopy, messages} from "share/common";
import wrapGuide from "components/method/wrapGuide";
import constants from "share/constants";
import moment from "moment/moment";
import UserMale from "images/user-male.png"
import UserFemale from "images/user-female.png"
import UserUnknow from 'images/user-unknow.png'
import CarouselPictrue from "containers/dashboard/dashboard-component/carousel-picture"
import CommonFunction from "containers/dashboard/dashboard-component/common-function"
import WaitApprove from "containers/dashboard/dashboard-component/wait-approve"
import DynamicDocuments from "containers/dashboard/dashboard-component/dynamic-documents"
import UpdateLog from "containers/dashboard/dashboard-component/update-log"
import Report from "containers/dashboard/dashboard-component/report"
import PendingRepayment from "containers/dashboard/dashboard-component/pending-repayment"
import AccountBook from "containers/dashboard/dashboard-component/account-book"
import BusinessCard from "containers/dashboard/dashboard-component/business-card";
import BusinessTravel from "containers/dashboard/dashboard-component/business-travel"
import "styles/dashboard/dashboard.scss"
import menuRoute from "routes/menuRoute";
import courseCn from "images/dashboard/course/course-zh_cn.png";
import courseTw from "images/dashboard/course/course-zh_tw.png";
import courseJa from "images/dashboard/course/course-ja.png";
import courseEn from "images/dashboard/course/course-en.png";
import DashboardService from 'containers/dashboard/dashboard.service';
import WaitSubmit from 'containers/dashboard/dashboard-component/wait-submit';
class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    const dragactInit = {
      containerWidth: 0,
      className: 'normal-layout',
      margin: [10, 10],
      col: 24,
      rowHeight: 16,
      layout: [],
      draggableHeight: 50
    };
    this.state = {
      dragactInit,
      imgBasicWidth: 1200, //轮播图标准图片宽度
      imgBasicHeight: 640, //轮播图标准图片高度
      isOperating: false, //拖拽布局操作状态
      target: "", //上午下午晚上
      tip: "",  //鸡汤
      loginUser: {}, //个人信息
      moduleSetShow: false, //模块设置侧拉框显示标志
      containerWidth: 0,  //右侧页面宽度
      imgWidth: 0,  //轮播图图片宽度
      imgProportion: 0, //轮播图图片比例
      FinancialCourse: menuRoute.getRouteItem('financial-course','key').url,
      shouldShowCourse: "",
      showCourse: "true",
      visible: false,
      key: 0
    };
    this.userImg = {
      0: UserMale,
      1: UserFemale,
      2: UserUnknow
    }
  }

  componentWillMount() {

    this.getPersonalInfo();
    //this.showCourse();
    this.setState({
      showCourse: localStorage.getItem("show-course"),
    });
    this.getAuthPersonInfo();
  }

  componentDidMount() {
    const {dragactInit, imgBasicHeight, imgBasicWidth} = this.state;
    let layout = localStorage.getItem("hly.layout") ? JSON.parse(localStorage.getItem("hly.layout")) : "";
    let containerWidth = document.getElementsByClassName("dashboard")[0].clientWidth - 8;
    let percent = imgBasicHeight / imgBasicWidth;
    let cardWidth = containerWidth / dragactInit.col * 8 - dragactInit.margin[1];
    window.addEventListener('resize', this.handleRisize)
    this.setState({
      containerWidth,
      imgWidth: cardWidth,
      imgProportion: percent
    }, () => {
      if (layout && layout.length && layout.length === 4) {
        this.setState({
          dragactInit: Object.assign(dragactInit, {containerWidth, layout})
        }, () => this.dashboardGuide());
        this.getLayoutData()
      } else {
        Promise.resolve()
          .then(() => this.getLayoutData())
          .then(() => this.dashboardGuide());
      }
    });
  }

  showCourse = () => {
    DashboardService.showCourse()
      .then(res => {
        this.setState({
          shouldShowCourse: res.data.result,
        })
      })
      .catch(err => {

    })
  };

  //获取个人信息板块详情，包括个人信息，当前时间，鸡汤
  getPersonalInfo = () => {
    let hour = moment().hour();
    let target = '';
    if (hour < 4) {
      target = 'night'
    } else if (hour < 12) {
      target = 'am'
    } else if (hour < 18) {
      target = 'pm'
    } else {
      target = 'night'
    }
    this.setState({
      target: target === "night" ? messages('dashboard.key15'/*晚上好*/) : (target === "am" ? messages('dashboard.key16'/*上午好*/) : messages('dashboard.key17'/*下午好*/)),
      tip: constants['dashboardTips'][target][Math.floor(Math.random() * 8)],
      loginUser: this.props.loginUser
    });
  };

  getLayoutData = () => {
    const { dragactInit, containerWidth, imgWidth, imgProportion } = this.state;
    let carouselHeight = imgWidth * imgProportion;
    let h = Math.round((carouselHeight + dragactInit.margin[0]) / (dragactInit.rowHeight + dragactInit.margin[0]));
    this.setState({
      dragactInit: Object.assign(dragactInit, {
        containerWidth,
        layout: [
          {w: 8, h: h, key: '0', order: 0, firm: true, show: true, removable: false, name: messages('dashboard.key141')/*公告*/},
          //{w: 8, h: h, key: '1', order: 1, minW: 300, minH: 150, show: true, removable: false, name: messages('dashboard.key131')/*常用功能*/},
          {w: 5.33, h: h, key: '1', order: 1, show: true, removable: true, name: messages('dashboard.key23'/*等待您处理的单据*/)},
          {w: 5.33, h: h, key: '2', order: 2, show: true, removable: true, name: messages('components.key1339'/*等待您提交的单据*/)},
          {w: 5.33, h: h, key: '3', order: 3, show: true, removable: true, name: messages('dashboard.key36'/*账本*/)},
          {w: 24, h: 14, key: '4', order: 4, show: true, removable: true, name: messages('dashboard.key26'/*单据动态*/)},
          //{w: 8, h: 14, key: '4', order: 4, show: true, removable: true, name: messages('dashboard.key152')/*更新日志*/},
          //{w: 24, h: 12, key: '5', order: 5, show: true, removable: true, name: messages('dashboard.key29'/*报表*/)},
          //{w: 8, h: 8, key: '6', order: 6, show: true, removable: true, name: messages('dashboard.key34'/*待还款*/)},
          //{w: 8, h: 8, key: '8', order: 8, show: true, removable: true, name: messages('dashboard.key40'/*商务卡*/)},
          //{w: 8, h: 8, key: '9', order: 9, show: true, removable: true, name: messages('dashboard.key43'/*商务出行*/)}
        ]
      })
    });
  };

  dashboardGuide = () => {
    let options = [{
      ref: this.refs.settingBtn,
      title: messages('dashboard.key145')/*首页设置*/,
      content: messages('dashboard.key146')/*这里可以自定义首页样式，快来试一试吧~*/,
      placement: "bottom",
      inline: "end",
      arrowStyle: {
        left: 300
      }
    }/*, {
      ref: this.refs.commonFuncBox,
      title: messages('dashboard.key131')/!*常用功能*!/,
      content: messages('dashboard.key147')/!*可以将经常使用的功能放到这里哦*!/,
      placement: "top",
      dynamic: true
    }*/];
    let config = {
      key: "DASHBOARD-0118",
      total: 1
    };
    !this.props.tenantMode && !window.ISIE9 && wrapGuide(options, config);
  };

  //查看首页拖拽布局的新手指引 isHard为true一定显示指引 为false第一次进入时才显示指引
  viewGuide = (isHard) => {
    let options = [{
      ref: document.getElementsByClassName("operate-item")[0],
      title: messages('dashboard.key145')/*首页设置*/,
      content: messages('dashboard.key148')/*这里可以设置模块的显示和隐藏*/,
      placement: "bottom",
      inline: "start"
    }, {
      ref: this.refs.accountBox,
      title: messages('dashboard.key145')/*首页设置*/,
      content: messages('dashboard.key149')/*1. 拖动模块可移动位置；*/ + "\n" + messages('dashboard.key150')/*2. 鼠标放在边缘可调整模块大小；*/,
      placement: "left",
      block: "start",
      dynamic: true
    },{
      ref: document.getElementsByClassName("operate-item")[3],
      title: messages('dashboard.key145')/*首页设置*/,
      content: messages('dashboard.key151')/*完成后点击这里回到正常使用*/,
      placement: "bottom",
      inline: "end",
      arrowStyle: {
        left: 290
      }
    }];
    let config = {
      key: "DASHBOARD-LAYOUT-0121",
      total: 3
    };
    if(isHard){
      let finishedGuide = localStorage.getItem('hly.guide') ? JSON.parse(localStorage.getItem('hly.guide')) : [];
      finishedGuide.indexOf(config.key) > -1 ? finishedGuide.splice(finishedGuide.indexOf(config.key), 1) : "";
      localStorage.setItem('hly.guide', JSON.stringify([...finishedGuide]));
    }
    wrapGuide(options, config);
  };

  //移除模块
  removeModule = (key) => {
    const {dragactInit} = this.state;
    dragactInit.layout.map(item => {
      if (item.key === key) {
        item.show = false;
      }
      return item
    });
    this.setState({dragactInit})
  };

  //刷新布局
  refreshLayout = (layout) => {
    if (JSON.stringify(layout) !== JSON.stringify(this.state.dragactInit.layout))
      this.setState({dragactInit: Object.assign(this.state.dragactInit, {layout})})
  };

  toggleSlideFrame = value => {
    this.setState({moduleSetShow: value})
  };

  checkCourse = () => {
    this.context.router.push(this.state.FinancialCourse);
  };

  onCloseCourse = (e) => {
    localStorage.setItem("show-course", "false");
    this.setState({
      showCourse: localStorage.getItem("show-course"),
    });
  };

  changeModal = () => {
    DashboardService.saveUserAuthorization().then(res => {
      if (res.status === 200) {
        this.setState({ visible: false });
      }
    })
  }

  getAuthPersonInfo = () => {
    DashboardService.getUserAuthorization().then(res => {
      console.log('res', res);
      if (res.status === 200) {
        this.setState({
          visible: !res.data
        })
      }
    }).catch(err => {
      message.error(err);
    })
  }

  handleRisize = (e) => {
    const {dragactInit, imgBasicHeight, imgBasicWidth} = this.state;
    let layout = localStorage.getItem("hly.layout") ? JSON.parse(localStorage.getItem("hly.layout")) : "";
    let containerWidth = document.getElementsByClassName("dashboard")[0].clientWidth - 8;
    console.log("containerWidth", containerWidth, e)
    let percent = imgBasicHeight / imgBasicWidth;
    let cardWidth = containerWidth / dragactInit.col * 8 - dragactInit.margin[1];
    this.setState({
      containerWidth,
      imgWidth: cardWidth,
      imgProportion: percent
    }, () => {
      this.setState({
        dragactInit: Object.assign(dragactInit, {containerWidth, layout}),
        isOperating: false
      }, () => {
        this.dashboardGuide()
        this.getLayoutData()
        this.viewGuide(true)
      });
    });
  }


  render() {
    const { isOperating, loginUser, dragactInit, target, tip, moduleSetShow, imgWidth, imgProportion, shouldShowCourse,
      showCourse
    } = this.state;
    const { tenantMode, user, language } = this.props;
    const backgroundImage = {
      "zh_cn": courseCn,
      "zh_tw": courseTw,
      "en": courseEn,
      "ja": courseJa,
    };
    let hideInUrl = window.location.href.indexOf("console-my.huilianyi.com") === -1 && window.location.href.indexOf("console-sg.huilianyi.com") === -1;
    return (
      <div className="dashboard background-transparent">
        <div className="helios-page-header">
          <Condition>
            {/*操作选项*/}
            <If value={isOperating}>
              <div className="operate">
                <h2>{messages('dashboard.key154')/*首页面板设置与隐藏*/}</h2>
                <p style={{marginBottom: 0}}>
                  <span className="operate-item" onClick={() => this.toggleSlideFrame(true)}>
                    <Icon type="tool" />{messages('dashboard.key155')/*设置可见模块*/}
                  </span>
                  <span className="operate-item" onClick={() => this.getLayoutData()}>
                    <Icon type="export" style={{transform: "rotate(180deg)"}} />{messages('dashboard.key156')/*恢复默认布局*/}
                  </span>
                  <span className="operate-item" onClick={() => this.viewGuide(true)}>
                    <Icon type="bars" />{messages('dashboard.key157')/*查看操作引导*/}
                  </span>
                  <span className="operate-item default-color-font f-right" onClick={() => this.setState({isOperating: false})}>
                    {messages('dashboard.key158')/*完成并退出*/}<Icon type="login" />
                  </span>
                </p>
              </div>
            </If>
            {/*个人信息*/}
            <Else>
              <Row className="personal-info">
                <Col span={2} className="user-img">
                  <img src={loginUser.filePath || this.userImg[loginUser.gender]} />
                </Col>
                <Col span={22} className="user-dep">
                  <h2>
                    {`${target}, ${loginUser.fullName}`}
                    <span>{loginUser.title && `${loginUser.title} | `}{loginUser.departmentName && loginUser.departmentName.split("|")[loginUser.departmentName.split("|").length - 1]}</span>
                  </h2>
                  {language.code === 'zh_cn' && <div className="dashboard-tip">"{tip}"</div>}
                </Col>
              </Row>
            </Else>
          </Condition>
          {/*拖拽布局操作按钮*/}
          <If value={!tenantMode && !window.ISIE9}>
            <Button ref="settingBtn" shape="circle" icon="setting" size="large" className={isOperating ? "hide" : "btn-operated"} onClick={() => this.setState({isOperating: !isOperating}, () => this.viewGuide())}/>
          </If>
        </div>
        {
          !tenantMode && (showCourse !== "false") &&
          ((!user.enableNewPermission && user.authorities.indexOf("ROLE_COMPANY_FINANCE_ADMIN") !== -1)
            || (user.enableNewPermission && user.hasFinanceRole)) && shouldShowCourse === "true" &&
            <div className="course-area"
                 style={{backgroundImage: `url('${backgroundImage[language.code.toLowerCase()]}')`,
                   backgroundPosition: "center", backgroundSize: "contain"
                 }}>
              <div className="course-area-content">
                <div className="course-area-btn" onClick={this.checkCourse}/>
                <div className="course-area-btn-text" onClick={this.checkCourse}>{messages('dashboard.key185')/*立即查看*/}</div>
                <div className="course-area-close"
                     onClick={this.onCloseCourse}><Icon type="close" />
                </div>
              </div>
            </div>
        }
        <Dragger {...dragactInit}
                 storageKey={'hly.layout'}
                 tenantMode={tenantMode}
                 isOperating={isOperating}
                 show={moduleSetShow}
                 toggleSlideFrame={this.toggleSlideFrame}
                 refresh={this.refreshLayout}>
          {/*公告信息，轮播图*/}
          <Card className="carousels" key="0">
            <CarouselPictrue imgWidth={imgWidth} imgProportion={imgProportion}/>
          </Card>
          {/*常用功能*/}
          {/*<Card className="common-func" key="1" ref="commonFuncBox">
            <CommonFunction tenantMode={tenantMode} removeModule={(key) => this.removeModule(key)}/>
          </Card>*/}
          {/*待审批单据*/}
          {
            !tenantMode &&
            <Card className="piechart" key="1">
              <WaitApprove removeModule={(key) => this.removeModule(key)}/>
            </Card>
          }
          {/*待提交单据*/}
          {
            !tenantMode &&
            <Card className="dashboard-sumbit-box" key="2">
              <WaitSubmit removeModule={(key) => this.removeModule(key)}/>
            </Card>
          }
          {/*账本*/}
          {
            !tenantMode &&
            <Card key="3" ref="accountBox">
              <AccountBook removeModule={(key) => this.removeModule(key)}/>
            </Card>
          }
          {/*单据动态*/}
          {
            !tenantMode &&
            <Card className="dynamic-document-card" key="4">
              <DynamicDocuments removeModule={(key) => this.removeModule(key)}/>
            </Card>
          }
          {/*更新日志*/}
          {/*{*/}
            {/*!tenantMode &&*/}
            {/*<Card className="document-card update-log"  key="4">*/}
              {/*<UpdateLog removeModule={(key) => this.removeModule(key)}/>*/}
            {/*</Card>*/}
          {/*}*/}
          {/*报表*/}
          {/*{
            !tenantMode &&
            <Card className="chart-card" key="5">
              <Report removeModule={(key) => this.removeModule(key)}/>
            </Card>
          }*/}
          {/*待还款*/}
          {/*{
            !tenantMode &&
            <Card key="6">
              <PendingRepayment removeModule={(key) => this.removeModule(key)}/>
            </Card>
          }*/}
          {/*商务卡*/}
          {/*{
            !tenantMode &&
            <Card key="8" ref="businessCard">
              <BusinessCard removeModule={(key) => this.removeModule(key)}/>
            </Card>
          }*/}
          {/*商务出行*/}
          {/*{
            !tenantMode && hideInUrl &&
            <Card key="9" className="supplier-card">
              <BusinessTravel removeModule={(key) => this.removeModule(key)}/>
            </Card>
          }*/}
        </Dragger>
        <Modal
          closable={false}
          keyboard={false}
          maskClosable={true}
          visible={this.state.visible}
          footer={<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <Button type="primary" onClick={this.changeModal}>同意</Button>
          </div>}
        >
          <div className="auth-modal-box">
            <img src="https://tes-static-1256351955.cos.ap-shanghai.myqcloud.com/company/logo/29ebb0bc-18c7-431f-85eb-d189feb53e07-McD_GoldenArches_1235_RGB.png" />
            <p>申明及确认</p>
            {/* <p>申明及签名</p> */}
            <div className="box-content">
            {/* <div>我，（{loginUser.fullName}），已仔细阅读并理解现行“麦当劳中国行政管理费用政策”（2018年1月版），并已被告知，如果违反以下规定，会导致根据公司人事政策规定的纪律处分：</div> */}
              {/* <div>我，（{loginUser.fullName}），已仔细阅读并理解现行“麦当劳中国行政管理费用政策”（2022年1月版），并已被告知，如果违反以下规定，会导致根据公司人事政策规定的纪律处分：</div> */}
              <div>我，（{loginUser.fullName}），已仔细阅读并理解现行“麦当劳中国行政管理费用政策”（2023年10月版），并已被告知，如果违反以下规定，会导致根据公司人事政策规定的纪律处分：</div>
              <div className="content-list">
                <span>1.违反公司商务行为标准以及反腐败政策；</span>
                {/* <span>1.违反公司商务行为标准及反腐败政策；</span> */}
                <span>2.用假发票或假收据报销，或用其它发票替代；</span>
                {/* <span>2.用假发票或假收据报销，或用其他发票替代；</span> */}
                <span>3.虚构业务报销；</span>
                <span>4.虚增参与人员及机构；</span>
                <span>5.修改发票抬头，或修改发票金额虚增报销费用；</span>
                <span>6.报销本规定或公司其他政策明确不予报销的项目；</span>
                <span>7.其他有证据可认定的虚报行为；</span>
                {/* <span>7.其他有证据可认定的虚报行为，如伪造批准人签字等；</span> */}
                <span>8.审批人未在合理范围内有效核查费用的合规合理及真实性。</span>
                {/* <span>8.审批人未有效检查费用的合规合理及真实性。</span> */}
              </div>
              <div>在此我郑重申明将严格遵守本政策，保证所有向公司报销的费用符合本政策规定，并为违反本政策的行为承担相应责任。</div>
              {/* <div>在此我郑重申明将严格遵守本政策，保证所有向公司报销的费用符合本政策规定，并为违反政策的行为承担相应责任。</div> */}
            </div>
          </div>
        </Modal>
      </div>
    )
  }
}

Dashboard.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
    tenantMode: state.main.tenantMode,
    authToken: state.main.authToken,
    language: state.main.language,
    user: state.login.user,
  }
}

export default connect(mapStateToProps)(Dashboard)
